import 'package:get/get.dart';
import 'package:meta/meta.dart';
import 'package:sqflite/sqflite.dart';
import 'package:xreader/db/sql_manager.dart';
import 'package:xreader/logs/log.dart';
import 'package:xreader/params/page_params.dart';
abstract class BaseDbProvider {
  bool isTableExits = false;

  String tableSqlString();

  List<String> tableIndexString(){
    return [];
  }

  String tableName();


  void limitSql(StringBuffer sb,PageParams param){
    sb.write(" limit ${param.pageSize} offset ${param.offset} ");
  }
  Future<int?> countTableRecordNum() async {
    Database? db = await getDataBase();
    if(db == null){
      return -1;
    }
    if(tableName().isEmpty){
      return -1;
    }
    return Sqflite.firstIntValue(await db.rawQuery(" select count(*) from  ${tableName()} "));
  }
  
  //根据id批量更新表字段值
  Future<int> updateColValueById(String tableNameStr,List<int> ids,String colName,int colValue) async{
    if(ids.isEmpty || colName.isEmpty){
      return 0;
    }
    Database? db = await getDataBase();
    if(db == null){
      return -1;
    }
    return db.update(tableNameStr,
      {colName:colValue},
      where:" id in ( ${ids.map((id) => '?').join(', ')} )",
      whereArgs: ids
    );
  }
  
  //判断是否需要同步
  Future<bool> needSync(int remoteNum) async {
      int localNum = await countTableRecordNum() ?? -1;
      return (localNum <= 0 || localNum != remoteNum);
  }

  //表+主键
  String tableBaseStringIntegerPrimarkKey(String name, String columnId) {
    return '''
        create table $name (
        $columnId integer primary key ,
      ''';
  }
  //表+主键
  String tableBaseStringTextPrimarkKey(String name, String columnId) {
    return '''
        create table $name (
        $columnId text primary key ,
      ''';
  }

  String tableBaseStringAutoPrimaryKey(String name, String columnId) {
    return '''
        create table $name (
        $columnId integer primary key autoincrement ,
      ''';
  }

  Future<Database?> getDataBase() async{
    return await open();
  }

  afterTableCreate(Database? db) async{

  }

  prepare(String name,String? createSql) async{
    isTableExits = await SqlManager.isTableExits(name);
    if(!isTableExits){
        print("$name 创建====》 $createSql");
        Database? db = await SqlManager.getCurrentDatabase();
        await db?.execute(createSql!);
        if(tableIndexString().isNotEmpty){
            try{
              tableIndexString().forEach((createIndexSql) async {
                  await db?.execute(createIndexSql);
              });
            }catch(e){
              print(e);
            }
        }
        try{
          await afterTableCreate(db);
        }catch(e){
          print(e);
        }

    }
  }
  @mustCallSuper
  Future<Database?> open() async{
    Log.i("${tableName()} isTableExits=${isTableExits}");
    if(!isTableExits){
      try{
        await prepare(tableName(),tableSqlString());
      }catch(e){
        Log.i("${tableName()} error================>$e");
      }
    }
    return await SqlManager.getCurrentDatabase();

  }




}